<template>
  <div class="enterprise-container">
    企业管理
    <div class="building-container">
      <!-- 搜索区域 -->
      <div class="search-container">
        <div class="search-label">企业名称：</div>

        <el-input clearable placeholder="请输入内容" class="search-main" />
        <el-button type="primary">查询</el-button>
      </div>

      <!-- 操作按钮 -->
      <div class="create-container">
        <el-button type="primary" @click="$router.push('/park/enterprise/add')">添加企业</el-button>
      </div>

      <!-- 表格区域 -->
      <div class="table">
        <!-- <el-table style="width: 100%" :data="list"> -->
        <el-table style="width: 100%" :data="list" @expand-change="expandChange">
          <!-- 展开的列 -->
          <el-table-column type="expand">
            <template #default>
              <el-table :data="rentList">
                <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
                <el-table-column label="租赁起始时间" prop="startTime" />
                <el-table-column label="合同状态" prop="status">
                  <!-- 作用域插槽 + 插值表达式来 渲染标签,对象中括号取值法 -->
                  <template slot-scope="scope">
                    <el-tag>{{ mapStatus[scope.row.status] }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                  <template #default="scope">
                    <el-button size="mini" type="text">退租</el-button>

                    <el-button size="mini" type="text">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>

          <el-table-column type="index" label="序号" />
          <el-table-column label="企业名称" width="320" prop="name" />
          <el-table-column label="联系人" prop="contact" />
          <el-table-column label="联系电话" prop="contactNumber" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="mini" type="text" @click="addRent">添加合同</el-button>

              <el-button size="mini" type="text">查看</el-button>

              <el-button size="mini" type="text">编辑</el-button>

              <el-button size="mini" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="page-container">
        <el-pagination layout="total, prev, pager, next" />
      </div>

      <!-- 添加合同对话框 -->
      <el-dialog title="添加合同" :visible="rentDialogVisible" width="580px" @close="closeDialog">
        <!-- 表单模版 -->
        <div class="form-container">
          <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
            <el-form-item label="租赁楼宇" prop="buildingId">
              <el-select v-model="rentForm.buildingId" placeholder="请选择">
                <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="租赁起止日期" prop="rentTime">
              <el-date-picker v-model="rentForm.rentTime" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd" />
            </el-form-item>

            <el-form-item label="租赁合同" prop="contractId">
              <el-upload action="#" :http-request="uploadFile">
                <el-button size="small" type="primary" plain>上传合同文件</el-button>

                <div slot="tip" class="el-upload__tip">
                  支持扩展名：.doc .docx .pdf, 文件大小不超过5M
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>

        <template #footer>
          <el-button size="mini" @click="closeDialog">取 消</el-button>

          <el-button size="mini" type="primary" @click="submitRentForm">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEnterpriseListAPI, getRentListAPI, getRentBuildListAPI, uploadAPI, createRentAPI, } from '@/api/enterprise'
export default {
  name: 'EnterPrise',
  data() {
    return {
      buildList: [],
      list: [], // 企业列表
      rentList: [], // 企业租赁信息列表
      mapStatus: {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      },
      rentDialogVisible: false, // 控制合同新增对话框显示和隐藏
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [{ required: true, message: '请上传合同文件' }]
      }
    }
  },
  created() {
    // 获取企业列表
    this.getList();

    // 获取楼宇下拉选项的数据
    this.getRentBuildList();
  },
  methods: {
    async submitRentForm() {
      try {
        // 1. 表单合法性验证
        await this.$refs.addForm.validate();

        // 2. 收集接口https://apifox.com/apidoc/shared-04b75e91-2e76-4a88-8774-6e5d65d14b61/api-128582353需要的请求数据
        let data = {
          buildingId: this.rentForm.buildingId,
          enterpriseId: this.rentForm.enterpriseId,
          startTime: this.rentForm.rentTime[0],
          endTime: this.rentForm.rentTime[1],
          contractId: this.rentForm.contractId,
          contractUrl: this.rentForm.contractUrl,
          type: 0, //添加合同
        };
        // console.log("新增合同data：", data);
        // return;

        // 3. 调用接口发送请求
        await createRentAPI(data);
        this.$message.success("新增合同成功");

        // 4. 关闭对话框
        this.rentDialogVisible = false;
      } catch (error) {
        console.log(error);
      }
    },
    // 上传合同
    async uploadFile(params) {
      // params是个对象，里面有一个File类型的属性->这个就是我们要上传的文件
      console.log("uploadFile", params.file);
      // 1. 创建 FormData对象
      const formData = new FormData();
      // 2. 使用formData对象的append方法添加参数
      formData.append("file", params.file);
      formData.append("type", "contract");
      // 3. 使用formData对象调用uploadAPI发送请求
      let res = await uploadAPI(formData);
      let { id, url } = res.data;
      this.rentForm.contractId = id;
      this.rentForm.contractUrl = url;
      // console.log();
    },
    // 获取楼宇数据
    async getRentBuildList() {
      let res = await getRentBuildListAPI();
      console.log(res.data);
      this.buildList = res.data;
    },
    closeDialog() {
      this.rentDialogVisible = false
    },
    // 打开添加合同的对话框
    addRent(row) {
      this.rentForm.enterpriseId = row.id;
      this.rentDialogVisible = true
    },
    async expandChange(row, expandedRows) {
      // 经过研究：row表示当前点击的那一行的数据，expandedRows：表示当前所有展开行数据
      console.log(row, expandedRows)
      // 优化：根据研究：发现row对象中的id如果在expandedRows中存在，则表示展开，就应该发送请求
      // 否则就是收起，不应该发请求
      // findIndex如果没有找到返回的是-1
      const index = expandedRows.findIndex((item) => item.id === row.id)

      if (index > -1) {
        // 1. 获取企业id
        // 2. 根据企业id获取租赁信息
        const res = await getRentListAPI(row.id)
        // console.log(res.data);
        this.rentList = res.data
      }
    }, async getList() {
      const res = await getEnterpriseListAPI({ page: 1, pageSize: 10 })
      this.list = res.data.rows
    }
  }
}
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
